package util

import (
	"fmt"
	"math/big"
	"net"
	"net/http"
	"regexp"
)

// 获取本机的 ip
func RemoteIp(req *http.Request) string {
	var remoteAddr string
	// RemoteAddr
	remoteAddr = req.RemoteAddr
	if remoteAddr != "" {
		return remoteAddr
	}
	// ipv4
	remoteAddr = req.Header.Get("ipv4")
	if remoteAddr != "" {
		return remoteAddr
	}
	//
	remoteAddr = req.Header.Get("XForwardedFor")
	if remoteAddr != "" {
		return remoteAddr
	}
	// X-Forwarded-For
	remoteAddr = req.Header.Get("X-Forwarded-For")
	if remoteAddr != "" {
		return remoteAddr
	}
	// X-Real-Ip
	remoteAddr = req.Header.Get("X-Real-Ip")
	if remoteAddr != "" {
		return remoteAddr
	} else {
		remoteAddr = "127.0.0.1"
	}
	return remoteAddr
}

// 校验ip地址
func JudgeIp(ip string) (ok bool) {
	return net.ParseIP(ip) != nil
}

// ip 转 10进制
func IpStringToInt(ip string) int64 {
	ret := big.NewInt(0)
	ret.SetBytes(net.ParseIP(ip).To4())
	return ret.Int64()
}

// 10进制 转 ip
func IpIntToString(ip int64) string {
	return fmt.Sprintf("%d.%d.%d.%d",
		byte(ip>>24), byte(ip>>16), byte(ip>>8), byte(ip))
}

// 输入地址是否在白名单中：：ipList 是用 | 分隔的字符串
func HadExist(ipList string, ip string) (ok bool, err error) {
	ok, err = regexp.MatchString(ipList, ip)
	return
}
